package socket.httpserver.singlefile;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HTTPHandler implements Callable<Void> {
    private static final Logger logger = Logger.getLogger("HTTPHandler");

    private final Socket connection;
    private final byte[] header;
    private final byte[] content;

    public HTTPHandler(Socket connection, byte[] header, byte[] content) {
        this.connection = connection;
        this.header = header;
        this.content = content;
    }

    @Override
    public Void call() throws Exception {
        try{
            OutputStream out = new BufferedOutputStream(connection.getOutputStream());
            InputStream in = new BufferedInputStream(connection.getInputStream());

            // 只读取一行，这是我们需要的全部内容
            StringBuilder request = new StringBuilder(80);
            while(true) {
                int c = in.read();
                if(c == '\r' || c == '\n' || c == -1) {
                    break;
                }
                request.append((char)c);
            }
            
            // HTTP/1.0 则发送一个MIME首部
            if(request.toString().indexOf("HTTP/") != -1) {
                out.write(header);
            }

            out.write(content);
            out.flush();
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error writing to client", e);
        } finally {
            connection.close();
        }
        return null;
    }
}
